"""
 *
 * This file is part of Pyphantom
 *
 * Copyright (C) 2007 Nokia Corporation
 *
 * Contact: Karoliina Salminen <karoliina.t.salminen@nokia.com>
 *
 * Author(s): Henry Vieira <henry.vieira@nokia.com>
 *            Edisson Braga <edisson.braga@indt.org.br>
 *            Rodrigo Belem <rodrigo.belem@indt.org.br>
 *
 * This package is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 dated June, 1991.
 *
 * This package is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this package; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 *
 *
"""

import os
import shutil
import tarfile
import subprocess
import pyphantom.arfile
import pyphantom.debconfigparser

try:
    from hashlib import md5
except:
    from md5 import md5


class DebHelper(object):

    def __init__(self, root_path, control, changelog):
        self.md5sum = md5()
        self.md5file = None
        self.debian_dst = None
        self.root_path = root_path
        self.deb_control = control
        self.deb_changelog = changelog
        os.chdir(self.root_path)
        self.genfiles = pyphantom.debconfigparser.GenFiles(self.deb_control, self.deb_changelog)

    def __create_md5sums(self, path):

        for item in os.listdir(path):
            item_path = os.path.join(path, item)
            if os.path.isfile(item_path):
                item_fd = open(item_path)
                self.md5sum.update(item_fd.read())
                item_fd.close()
                # TODO: force / separator
                self.md5file.write('%s %s\n' % (
                                    self.md5sum.hexdigest(),
                                    item_path[len(self.debian_dst)+1:]))

            elif os.path.isdir(item_path):
                self.__create_md5sums(item_path)

    def _install_files(self):
        dest_dir = os.path.join(self.root_path, 'debian', 'tmp')
        a = subprocess.Popen('python setup.py install --root=%s' % dest_dir, shell=True)
        a.wait()
        
    def _install_deb(self):

        os.chdir(self.root_path)
        self.md5file = open(os.path.join('debian', 'md5sums'), 'w')
        self.debian_dst = os.path.join('debian', 'tmp')
        self.__create_md5sums(os.path.join('debian', 'tmp'))
        self.md5file.close()
        os.makedirs(os.path.join('debian', 'tmp', 'DEBIAN'))
        shutil.move(os.path.join('debian', 'md5sums'), os.path.join('debian',
                                    'tmp', 'DEBIAN'))
        self.genfiles.gencontrol(self.pkgname,
                                    os.path.join(self.root_path,
                                                    'debian',
                                                    'tmp',
                                                    'DEBIAN',
                                                    'control'))
        os.chdir(self.root_path)

    def __create_data(self):

        os.chdir(self.root_path)
        # creating the data.tar.gz with the contents of tmp dir
        tar_file = tarfile.open(os.path.join('debian', 'data.tar.gz'), 'w:gz')
        os.chdir(os.path.join('debian', 'tmp'))

        file_list = os.listdir('.')
        if 'DEBIAN' in file_list:
            file_list.remove('DEBIAN')

        for item in file_list:
            tar_file.add(item)
        tar_file.close()

        os.chdir(self.root_path)

    def __create_control(self):

        os.chdir(self.root_path)

        tar_file = tarfile.open(os.path.join('debian', 'control.tar.gz'), 'w:gz')
        os.chdir(os.path.join('debian', 'tmp', 'DEBIAN'))

        tar_file.add('.')
        tar_file.close()

        os.chdir(self.root_path)

    def __create_debian_binary(self):
        os.chdir(self.root_path)

        fd = open(os.path.join('debian', 'debian-binary'), 'w')
        fd.write('2.0\n')
        fd.close()

        os.chdir(self.root_path)

    def __clean_target(self):
        path = os.path.join('debian', 'tmp')
        if os.path.exists(path):
            shutil.rmtree(path)

    def create_dot_deb(self, dest_file):
        os.chdir(self.root_path)

        self.__clean_target()
        # FIXME: creating package just of the first Package entry in source control
        self.pkgname = self.deb_control.sections()[0]
        self._install_files()
        self._install_deb()
        self.__create_data()
        self.__create_control()
        self.__create_debian_binary()

        os.chdir(self.root_path)
        os.chdir('debian')
        deb_file = pyphantom.arfile.ArFile()
        # this list order must be followed
        for item in ['debian-binary', 'control.tar.gz', 'data.tar.gz']:
            deb_file.files.append(item)
        deb = open(dest_file, 'w') 
        deb.write(deb_file.packed())
        deb.close()
        for item in ['debian-binary', 'control.tar.gz', 'data.tar.gz']:
            os.remove(item)

        os.chdir(self.root_path)
        self.__clean_target()

